package com.coldlz.mmp.ssl;

import com.coldlz.mmp.proxy.ProxyException;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.operator.OperatorCreationException;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class DefaultCASignerProvider implements CASignerProvider {

    private final KeyPairStr caKeyPair;
    private final X509Certificate caCert;

    public DefaultCASignerProvider(KeyPairStr caKeyPair, X509Certificate caCert) {
        this.caKeyPair = caKeyPair;
        this.caCert = caCert;
    }

    @Override
    public X509Certificate signature(X509v3CertificateBuilder certBuilder) {
        try {
            return CertificateInfoHelper.signature(certBuilder, caKeyPair);
        } catch (IOException | CertificateException | OperatorCreationException | NoSuchAlgorithmException |
                 SignatureException | InvalidKeyException | NoSuchProviderException e) {
            throw new ProxyException(e);
        }
    }

    @Override
    public AuthorityKeyIdentifier authorityKeyIdentifier() {
        return CertificateInfoHelper.getAuthorityKeyIdentifier(caCert);
    }

    @Override
    public X500Name issuer() {
        return CertificateInfoHelper.getIssuer(caCert);
    }
}